<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
	</head>
	<script type="text/javascript">
		//用于填写发送消息的输入框
		var messageBox;
		//用于显示消息的div容器
		var messageLog;
		//WebSocket对象
		var socket;
		var send;
		var receive;

		//页面加载完毕
		window.onload = function() {
			messageBox = document.getElementById('messageBox');
			messageLog = document.getElementById('messageLog');
			send = document.getElementById('sendId');
			receive = document.getElementById('receiveId');
		}

		//创建socket对象并绑定所有事件
		function connect() {
			var sendId = send.value;
			//创建socket对象
			socket = new WebSocket("ws://127.0.0.1:8081/echo?sendId="+sendId);

			//监听所有的Web socket事件
			socket.onopen = connectionOpen;
			socket.onmessage = messageReceived;
			socket.onerror = errorOccurred;
			socket.onclose = connectionClosed;
		}

		//断开连接按钮点击
		function disconnect() {
			socket.close();
		}

		//发送消息按钮点击
		function sendMessage() {
			//获取要发送的数据
			var receiveId = receive.value;
			var message = messageBox.value;
			var obj = {};
			obj['receiveId'] = receiveId;
			obj['message'] = message;
			//通过socket发送消息
			socket.send(JSON.stringify(obj));
			
			// 通过接口发送消息
			

			//告诉用户刚刚发生了什么
			messageLog.innerHTML += "<br>发送：" + message;
		}

		//连接建立完毕事件响应
		function connectionOpen(e) {
			messageLog.innerHTML += "<br>--- Socket连接成功 ---";
		}

		//消息接收事件响应
		function messageReceived(e) {
			messageLog.innerHTML += "<br>收到：" + e.data;
		}

		//错误事件响应
		function errorOccurred(e) {
			messageLog.innerHTML += "<br>发生错误：" + e.data;
		}

		//连接关闭事件响应
		function connectionClosed(e) {
			messageLog.innerHTML += "<br>--- Socket连接关闭 ---";
		}
	</script>
	</head>
	<body>
		登录账号：<input id="sendId" type="text" />
		发送用户：<input id="receiveId" type="text" />
		消息：<input id="messageBox" type="text" />
		<button onclick="connect()">连接</button>
		<button onclick="sendMessage()">发送</button>
		<button onclick="disconnect()">断开</button>
		<div id="messageLog"></div>
	</body>
</html>
